package TAIC.util ;
 
public class ThreadPool {
    public ThreadPool ( int max ) {
        maxThread = max ;
        pool = new Thread [ maxThread ] ; 
    }
    	
    synchronized public void addThread ( Runnable thread ) {
        int i ; 
        while ( true ){
            for ( i = 0 ; i< maxThread ; i ++ )
                if ( pool [ i ] == null || !pool [ i ].isAlive() ) break ;
            if ( i < maxThread ) break ;
            else try {
                Thread.sleep ( 1000 ) ;
            }catch (Exception e ) {
                e.printStackTrace () ;
            };
        }
        pool [ i ] = new Thread ( thread ) ; 
        pool [ i ].start () ; 
    }
    
    public void join () {
        for ( int i = 0 ; i < maxThread ; i ++ )
            if ( pool [ i ] != null && pool [ i ].isAlive () ) try {
				Thread.sleep ( 20000 ) ;
                //pool [ i ].join( 10000 ) ;
				if ( pool [ i ].isAlive () ) {
					System.out.println ( "Thread " + ( i + 1 ) + " had been forced stop." ) ;
					pool [ i ].interrupt()   ;
				}
//				System.out.println ( "Thread " + ( i + 1 ) + " ended." ) ; 
            }catch ( Exception e ) {
                e.printStackTrace () ; 
            }
    }
    
    private int maxThread  ;
    private Thread pool [ ] ; 

}
